package juc.executors;

import java.util.concurrent.*;

public class FutureExample1 {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        testGet();
    }

    /**
     * dist cp
     * yarn applicationJobId
     * process
     * kill -9 process
     * yarn -kill applicationJobId
     *
     * {@link Future#get()}
     * InterruptedException是谁抛出的？
     */
    private static void testGet() throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<Integer> future = executorService.submit(() -> {
            timeSleep(2);
            System.out.println("===");
            return 10;
        });

        System.out.println("===i will be printed quickly");
        //
        Thread callerThread = Thread.currentThread();
        System.out.println(callerThread.getName());
        new Thread(() -> {
            callerThread.interrupt();
        }).start();

        //会block，可以被interrupt，可以被cancel
        //main线程get陷入阻塞，所以打断的是main线程
        //get调用超时。线程池任务还会继续执行
        Integer result = future.get(5,TimeUnit.SECONDS);
        System.out.println("===" + result);
    }

    private static void timeSleep(long time) {
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
